let [
    form,
    btn,
    notice,
] =
    [
        document.getElementById("fm1"),
        document.getElementById("wtjloginBtn"),
        document.getElementById("box"),
    ];
form.addEventListener("submit", evt => {
    let e = evt || window.event;
    e.preventDefault();
})
btn.addEventListener("click", evt => {
    let [
        userValue,
        pwdVale,
    ] = [
            document.getElementById("loginEmail").value,
            document.getElementById("loginPass").value,
        ]
    let url = "http://localhost/wuTuoJia_project/src/html/login.php";
    // let data = {
    //     username : userValue,
    //     password : pwdVale,
    // }
    let data = "username=" + userValue + "&" + "password=" + pwdVale;

    //禁用按钮;
    btn.disables = "disabled";
    btn.innerHTML = "loading";

    $.ajax({
        url,
        data,
        type: "POST",
        dataType: "json"
    })
        .then(res => {
            console.log(res.stateCode);
            switch (res.stateCode) {
                case 0: alert("登录参数不全");
                    break;
                case 2: alert("数据库链接失败");
                    break;
                case 3: alert("用户名不存在");
                    break;
                case 4: alert("密码错误");
                    break;
                case 1: alert("登录成功");
                    location.reload();
                    break;
            }
            btn.removeAttribute("disabled");
            btn.innerHTML = "登录";
            console.log(res);
        })
})
// 先发一个请求,验证是否存在tocken,如果存在就不用登录了,如果不存在,继续登录;
function validateTocken() {
    let url = "http://localhost/wuTuoJia_project/src/html/login.php";
    $.ajax(
        {
            url,
        })
        .then(res => {
            // console.log(res);
            res = JSON.parse(res);
            if (res.state) {
                return false;
            }
            //    body.innerHTML = "用户名:" +res.username+ "<button id = 'exit'> 退出登录</button>";
            notice.innerHTML = `
                            <p class='user'>用户名:"${res.username} "</p>
                            <h2>已成功登录!</h2>
                            <button id = 'exit'> 退出登录</button>
                            `;
            notice.style.background = "inherit";

            let exit = document.getElementById("exit");
            exit.addEventListener("click",evt=>{
                var d= new Date();
                d.setDate(d.getDate()-1);
                document.cookie = "TOCKEN='';expires=" + d; 
                location.reload();
            })
        })
}
validateTocken();